<?php
/**
 * 易优CMS
 * ============================================================================
 * 版权所有 2016-2028 海南赞赞网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.eyoucms.com
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 陈风任 <491085389@qq.com>
 * Date: 2022-03-23
 */

namespace app\plugins\model;

use think\Db;
use think\Page;
use think\Model;
use think\Config;

/**
 * 模型
 */
class MultiMerchant extends Model
{
    //初始化
    protected function initialize()
    {
        // 需要调用`Model`的`initialize`方法
        parent::initialize();

        // 商家主表
        $this->multiMerchantDb = Db::name('WeappMultiMerchant');
    }

    // 商家概况信息
    public function getMerchantOverview($merchant_id = 0)
    {
        // 今日时间戳
        $todayTime = strtotime(date('Y-m-d'));
        $todayTimeEnd = intval($todayTime) + 86399;
        // 昨日时间戳
        $yesterdayTime = strtotime(date('Y-m-d',strtotime('-1 day')));
        $yesterdayTimeEnd = intval($yesterdayTime) + 86399;
        // 待付款订单、待发货订单
        $pendingPayNum = $pendingSendNum = $todayOrder = $yesterdayOrder = $allSales = $todaySales = $yesterdaySales = 0;
        // 订单数据处理
        $allOrder = $this->getMerchantAllOrderList($merchant_id);
        foreach ($allOrder as $key => $value) {
            // 待付款订单
            if (0 == $value['order_status']) {
                $pendingPayNum++;
            }
            // 待发货订单
            else if (1 == $value['order_status']) {
                $pendingSendNum++;
            }
            // 只计算已付款之后的订单
            if ($value['order_status'] > 0) {
                // 所有订单销量额
                $allSales = floatval($allSales) + floatval($value['order_amount']);
                // 今天的订单
                if ($value['add_time'] > $todayTime && $value['add_time'] < $todayTimeEnd) {
                    $todayOrder++;
                    $todaySales = floatval($todaySales) + floatval($value['order_amount']);
                }
                // 昨日时间戳
                else if ($value['add_time'] > $yesterdayTime && $value['add_time'] < $yesterdayTimeEnd) {
                    $yesterdayOrder++;
                    $yesterdaySales = floatval($todaySales) + floatval($value['order_amount']);
                }
            }
        }

        // 返回数据
        $result = [
            // 待付款订单
            'pendingPay' => [
                'num' => $pendingPayNum,
                'url' => url('plugins/MultiMerchant/order', ['order_status' => 10]),
            ],
            // 待发货订单
            'pendingSend' => [
                'num' => $pendingSendNum,
                'url' => url('plugins/MultiMerchant/order', ['order_status' => 1]),
            ],
            // 售后服务单
            'serviceOrder' => [
                'num' => Db::name('shop_order_service')->where(['merchant_id' => $merchant_id])->count('service_id'),
                'url' => url('plugins/MultiMerchant/service'),
            ],
            // 商品待审核
            'auditProduct' => [
                'num' => Db::name('archives')->where(['is_del' => 0, 'arcrank' => -1, 'merchant_id' => $merchant_id])->count('aid'),
                'url' => url('plugins/MultiMerchant/product', ['query' => 4]),
            ],
            // 订单数据
            'order' => [
                'allOrder' => count($allOrder),
                'todayOrder' => $todayOrder,
                'yesterdayOrder' => $yesterdayOrder,
                'allSales' => floatval($allSales),
                'todaySales' => $todaySales,
                'yesterdaySales' => $yesterdaySales,
                'orderUrl' => url('plugins/MultiMerchant/order'),
                'salesUrl' => url('plugins/MultiMerchant/asset_order'),
            ],
            // 发布商品页
            'productAdd' => url('plugins/MultiMerchant/product_add'),
        ];

        return $result;
    }

    // 查询商家信息
    public function getFindMerchant($id = 0, $field = 'merchant_id')
    {
        // 查询商家信息
        $where = [
            'is_del' => 0,
            $field => $id,
        ];
        $multiMerchant = $this->multiMerchantDb->where($where)->find();
        if (empty($multiMerchant)) return false;

        // 图片集解析
        $multiMerchant['merchant_pic'] = !empty($multiMerchant['merchant_pic']) ? unserialize($multiMerchant['merchant_pic']) : [];
        if (!empty($multiMerchant['merchant_pic']['merchant_logo'])) {
            $multiMerchant['merchant_pic']['merchant_logo'] = handle_subdir_pic(get_default_pic($multiMerchant['merchant_pic']['merchant_logo']));
        } else {
            $multiMerchant['merchant_pic']['merchant_logo'] = handle_subdir_pic(get_default_pic());
        }

        // 商家介绍解析
        $multiMerchant['merchant_content'] = !empty($multiMerchant['merchant_content']) ? unserialize($multiMerchant['merchant_content']) : '';

        // 商家联系地址解析
        $multiMerchant['merchant_contact'] = !empty($multiMerchant['merchant_contact']) ? unserialize($multiMerchant['merchant_contact']) : [];

        // 商家收货地址解析
        $multiMerchant['merchant_service'] = !empty($multiMerchant['merchant_service']) ? unserialize($multiMerchant['merchant_service']) : [];

        // 申请认证信息解析
        $multiMerchant['apply_data'] = !empty($multiMerchant['apply_data']) ? unserialize($multiMerchant['apply_data']) : [];
        if (!empty($multiMerchant['apply_data']['personal']['personalIDCardFront'])) {
            $multiMerchant['apply_data']['personal']['personalIDCardFront'] = handle_subdir_pic(get_default_pic($multiMerchant['apply_data']['personal']['personalIDCardFront']));
        } else {
            $multiMerchant['apply_data']['personal']['personalIDCardFront'] = handle_subdir_pic(get_default_pic());
        }
        if (!empty($multiMerchant['apply_data']['personal']['personalIDCardReverse'])) {
            $multiMerchant['apply_data']['personal']['personalIDCardReverse'] = handle_subdir_pic(get_default_pic($multiMerchant['apply_data']['personal']['personalIDCardReverse']));
        } else {
            $multiMerchant['apply_data']['personal']['personalIDCardReverse'] = handle_subdir_pic(get_default_pic());
        }
        if (!empty($multiMerchant['apply_data']['company']['legalPersonalIDCardFront'])) {
            $multiMerchant['apply_data']['company']['legalPersonalIDCardFront'] = handle_subdir_pic(get_default_pic($multiMerchant['apply_data']['company']['legalPersonalIDCardFront']));
        } else {
            $multiMerchant['apply_data']['personal']['legalPersonalIDCardFront'] = handle_subdir_pic(get_default_pic());
        }
        if (!empty($multiMerchant['apply_data']['company']['legalPersonalIDCardReverse'])) {
            $multiMerchant['apply_data']['company']['legalPersonalIDCardReverse'] = handle_subdir_pic(get_default_pic($multiMerchant['apply_data']['company']['legalPersonalIDCardReverse']));
        } else {
            $multiMerchant['apply_data']['personal']['legalPersonalIDCardReverse'] = handle_subdir_pic(get_default_pic());
        }
        if (!empty($multiMerchant['apply_data']['company']['businessLicencePic'])) {
            $multiMerchant['apply_data']['company']['businessLicencePic'] = handle_subdir_pic(get_default_pic($multiMerchant['apply_data']['company']['businessLicencePic']));
        } else {
            $multiMerchant['apply_data']['personal']['businessLicencePic'] = handle_subdir_pic(get_default_pic());
        }

        // 商家结算信息解析
        $multiMerchant['settle_data'] = !empty($multiMerchant['settle_data']) ? unserialize($multiMerchant['settle_data']) : [];

        // 商家首页地址
        $multiMerchant['merchant_url'] = url('home/MultiMerchant/merchant_index', ['merchant_id'=>$multiMerchant['merchant_id']]);

        // 返回数据
        return $multiMerchant;
    }

    // 添加商家信息
    public function addFindMerchant($post = [], $users_id = 0)
    {
        // 系统时间
        $time = getTime();

        // 处理商家图片(商家LOGO)数据
        $merchantPic = [
            'merchant_logo' => $post['merchant_pic'],
        ];

        // 添加商家信息
        $insert = [
            // post信息
            'users_id' => $users_id,
            'merchant_name' => strval($post['merchant_name']),
            'merchant_industry' => strval($post['merchant_industry']),
            'merchant_pass' => md5(intval($post['merchant_pass'])),
            'merchant_phone' => intval($post['merchant_phone']),
            'merchant_pic' => serialize($merchantPic),
            'merchant_content' => !empty($post['merchant_content']) ? serialize($post['merchant_content']) : strval($post['merchant_name']) . '介绍',
            // 默认填充字段，防止兼容性报错
            'merchant_contact' => '',
            'merchant_service' => '',
            'apply_type' => 0,
            'apply_data' => '',
            'settle_type' => 0,
            'settle_data' => '',
            'extend_field' => '',
            // 系统时间信息
            'login_time' => $time,
            'add_time' => $time,
            'update_time' => $time
        ];

        // 执行添加
        $insertID = $this->multiMerchantDb->insertGetId($insert);
        if (!empty($insertID)) {
            // 返回结果
            return $insert;
        } else {
            return false;
        }
    }

    // 保存商家信息
    public function updateFindMerchant($post = [], $users_id = 0)
    {
        // 系统时间
        $time = getTime();

        // 处理商家图片(商家LOGO)数据
        $merchantPic = [
            'merchant_logo' => $post['merchant_pic'],
        ];

        // 保存商家信息
        $update = [
            // 主键ID
            'merchant_id' => intval($post['merchant_id']),
            // post信息
            'users_id' => $users_id,
            'merchant_name' => strval($post['merchant_name']),
            'merchant_industry' => strval($post['merchant_industry']),
            'merchant_phone' => intval($post['merchant_phone']),
            'merchant_pic' => serialize($merchantPic),
            'merchant_content' => !empty($post['merchant_content']) ? serialize($post['merchant_content']) : strval($post['merchant_name']) . '介绍',
            // 系统时间信息
            'update_time' => $time
        ];

        // 若提交密码则执行
        if (!empty($post['merchant_pass'])) {
            $update['login_time'] = $time;
            $update['merchant_pass'] = md5(intval($post['merchant_pass']));
        }

        // 执行添加
        $updateID = $this->multiMerchantDb->update($update);
        if (!empty($updateID)) {
            // 返回结果
            if (!empty($post['merchant_pass'])) {
                return $update;
            } else {
                return true;
            }
        } else {
            return false;
        }
    }

    // 提交商家认证申请，更新商家信息
    public function certFindMerchant($post = [], $merchant_id = 0, $edit = false)
    {
        // 申请商家认证信息
        $apply_data = [];
        if (!empty($post['personal'])) $apply_data['personal'] = $post['personal'];
        if (!empty($post['company'])) $apply_data['company'] = $post['company'];

        $update = [
            'merchant_id' => $merchant_id,
            // 申请商家认证信息
            'apply_type' => intval($post['apply_type']),
            'apply_data' => serialize($apply_data),
            // 商家结算信息
            'settle_type' => intval($post['settle_type']),
            'settle_data' => serialize($post['settle']),
            // 默认待审核状态
            'audit_status' => 1,
            // 系统信息
            'update_time' => getTime(),
        ];
        // $update['apply_data'] = unserialize($update['apply_data']);
        // $update['settle_data'] = unserialize($update['settle_data']);
        // dump($update);exit;
        // 执行添加
        $updateID = $this->multiMerchantDb->update($update);
        if (!empty($updateID)) {
            // 返回结果
            return true;
        } else {
            return false;
        }
    }

    // 更新商家联系地址
    public function updateMerchantContact($post = [], $merchant_id = 0)
    {
        // 系统时间
        $time = getTime();

        // 添加商家信息
        $update = [
            // 商家ID
            'merchant_id' => $merchant_id,
            // post信息
            'merchant_contact' => serialize($post['contact']),
            // 'merchant_service' => serialize($post['service']),
            // 系统信息
            'update_time' => $time
        ];
        // $update['merchant_contact'] = unserialize($update['merchant_contact']);
        // $update['merchant_service'] = unserialize($update['merchant_service']);
        // dump($update);exit;
        // 执行添加
        $updateID = $this->multiMerchantDb->update($update);
        if (!empty($updateID)) {
            // 返回结果
            return true;
        } else {
            return false;
        }
    }


    // -------- 订单部分
    // 获取商家全部订单信息(不分页)
    public function getMerchantAllOrderList($merchant_id = 0)
    {
        // 查询商品的全部订单
        $where = [
            'merchant_id' => $merchant_id
        ];
        $field = 'order_id, order_code, users_id, merchant_id, order_status, order_amount, pay_name, order_terminal, add_time';
        $shopOrder = Db::name('shop_order')->field($field)->where($where)->select();

        // 返回数据
        return $shopOrder;
    }

    // 获取商家订单列表(有分页)
    public function getMerchantOrderList($merchant_id = 0)
    {
        // 查询条件
        $where = [
            'a.merchant_id' => $merchant_id
        ];

        // 返回参数
        $param = [];

        // 订单号查询
        $param['keywords'] = input('keywords/s', '');
        if (!empty($param['keywords'])) $where['a.order_code'] = ['LIKE', "%{$param['keywords']}%"];

        // 支付方式查询
        $param['pay_name'] = input('pay_name/s', '');
        if (!empty($param['pay_name'])) $where['a.pay_name'] = $param['pay_name'];

        // 订单下单终端查询
        $param['order_terminal'] = input('order_terminal/d', 0);
        if (!empty($param['order_terminal'])) $where['a.order_terminal'] = $param['order_terminal'];

        // 商品类型查询
        $param['contains_virtual'] = input('contains_virtual/d', 0);
        if (!empty($param['contains_virtual'])) $where['a.contains_virtual'] = $param['contains_virtual'];

        // 订单状态查询
        $param['order_status'] = input('order_status/s', 0);
        if (!empty($param['order_status'])) $where['a.order_status'] = 10 === intval($param['order_status']) ? 0 : $param['order_status'];
        if (!empty($param['order_status']) && 99 === intval($param['order_status'])) $where['a.order_status'] = ['IN', [0, 1, 2]];

        // 发布时间查询
        $param['add_time'] = input('add_time/s', '');
        if (!empty($param['add_time'])) {
            $add_time = explode('~', $param['add_time']);
            $begin = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]));
            $where['add_time'] = ['between', "$begin, $finish"];
        }

        // 订单完成时间查询
        $param['confirm_time'] = input('confirm_time/s', '');
        if (!empty($param['confirm_time'])) {
            $confirm_time = explode('~', $param['confirm_time']);
            $begin = strtotime(rtrim($confirm_time[0]));
            $finish = strtotime(rtrim($confirm_time[1]));
            $where['confirm_time'] = ['between', "$begin, $finish"];
        }
        // dump($where);exit;

        // 分页查询
        $count = Db::name('shop_order')->alias('a')->where($where)->count('order_id');
        $pageObj = new Page($count, config('paginate.list_rows'));

        // 订单主表数据查询
        $list = Db::name('shop_order')->alias('a')
            ->field('a.*, b.username as u_username, b.nickname as u_nickname, b.mobile as u_mobile')
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->order('a.order_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();
        if (empty($list) && !empty($param['keywords'])) {
            // 通过商品名称查询订单号
            $where_1['product_name'] = ['LIKE', "%{$param['keywords']}%"];
            $order_ids = Db::name('shop_order_details')->where($where_1)->group('order_id')->column('order_id');
            if (!empty($order_ids)) {
                // 重新查询订单主表
                unset($where['a.order_code']);
                $where['a.order_id'] = ['IN', $order_ids];
                // 分页查询
                $count = Db::name('shop_order')->alias('a')->where($where)->count('order_id');
                $pageObj = new Page($count, config('paginate.list_rows'));
                // 订单主表数据查询
                $list = Db::name('shop_order')->alias('a')
                    ->field('a.*, b.username as u_username, b.nickname as u_nickname, b.mobile as u_mobile')
                    ->where($where)
                    ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
                    ->order('a.order_id desc')
                    ->limit($pageObj->firstRow.','.$pageObj->listRows)
                    ->select();
            } else {
                $list = [];
            }
        }

        // 提取订单ID
        $order_ids = [];
        $OrderReminderID = [];
        foreach ($list as $key => $value) {
            array_push($order_ids, $value['order_id']);
            if (1 == $value['order_status']) array_push($OrderReminderID, $value['order_id']);
        }

        // 处理订单详情数据
        $where = [
            'a.order_id' => ['IN', $order_ids]
        ];
        $DetailsData = Db::name('shop_order_details')->alias('a')
            ->field('a.*, b.service_id, b.status')
            ->where($where)
            ->join('__SHOP_ORDER_SERVICE__ b', 'a.details_id = b.details_id', 'LEFT')
            ->order('details_id asc')
            ->select();
        $ArchivesData = get_archives_data($DetailsData, 'product_id');
        $OrderServiceStatus = Config::get('global.order_service_status');
        foreach ($DetailsData as $key => $value) {
            // 售后信息处理
            $value['service_id'] = !empty($value['service_id']) ? $value['service_id'] : 0;
            $value['status'] = !empty($value['status']) ? $value['status'] : 0;
            $value['status_name'] = !empty($value['status']) ? $OrderServiceStatus[$value['status']] : '';
            // 产品属性处理
            $value['data'] = unserialize($value['data']);
            $value['data'] = htmlspecialchars_decode(htmlspecialchars_decode($value['data']['spec_value']));
            // 组合数据
            $value['data'] = explode('<br/>', $value['data']);
            $valueData = '';
            foreach ($value['data'] as $key_1 => $value_1) {
                if (!empty($value_1)) $valueData .= '<span>' . trim(explode('：', $value_1)[1]) . '</span>';
            }
            $value['data'] = $valueData;
            if (!empty($ArchivesData[$value['product_id']])) {
                $value['arcurl'] = arcurl('home/Product/view', $ArchivesData[$value['product_id']]);
                $value['product_del'] = '';
            } else {
                $value['arcurl'] = 'JavaScript:void(0);';
                $value['product_del'] = '商品已删除';
            }
            $value['litpic'] = handle_subdir_pic(get_default_pic($value['litpic']));
            $DetailsData[$key] = $value;
        }

        // 获取订单方式名称
        $payMethodArr = Config::get('global.pay_method_arr');
        // 把订单详情数据植入订单数据
        $DetailsDataGroup = group_same_key($DetailsData, 'order_id');
        foreach ($list as $key => $value) {
            // 处理会员昵称
            $value['u_nickname'] = !empty($value['u_nickname']) ? $value['u_nickname'] : $value['u_username'];
            // 处理订单详情数据
            $value['Details'] = $DetailsDataGroup[$value['order_id']];
            // 商品条数
            $value['rowspan'] = count($value['Details']);
            // 添加时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            // 确认收货时间(完成时间)
            $value['confirm_time'] = !empty($value['confirm_time']) ? date('Y-m-d H:i:s', $value['confirm_time']) : '未完成';
            // 更新时间
            $value['update_time'] = date('Y-m-d H:i:s', $value['update_time']);
            // 支付方式
            $value['pay_name'] = !empty($payMethodArr[$value['pay_name']]) ? $payMethodArr[$value['pay_name']] : '未付款';
            // 重新赋值数据
            $list[$key] = $value;
        }

        // 分页显示输出
        $pageStr = $pageObj->show();
        // 开启的商城商品类型
        $shopType = intval(getUsersConfigData('shop.shop_type'));
        // 是否安装 可视化微信小程序（商城版） ，未安装开启则不显示小程序支付
        $where = [
            'status' => 1,
            'code' => 'DiyminiproMall'
        ];
        $openMall = Db::name('weapp')->where($where)->count();
        // 查询订单被提醒发货次数
        $remind = [];
        if (!empty($OrderReminderID)) {
            $field = 'order_id, count(action_id) as action_count';
            $group = 'order_id';
            $where = [
                'action_desc' => '提醒成功！',
                'order_id' => ['IN', $OrderReminderID]
            ];
            $remind = Db::name('shop_order_log')->field($field)->group($group)->where($where)->getAllWithIndex('order_id');
        }

        // 返回加载页面信息
        return [
            'list' => $list,
            'param' => $param,
            'page' => $pageStr,
            'pager' => $pageObj,
            'remind' => $remind,
            'shopType' => $shopType,
            'openMall' => $openMall,
        ];
    }

    // 查询商家订单详情信息
    public function getMerchantOrderDetails($merchant_id = 0, $order_id = 0)
    {
        // 获取订单数据
        $where = [
            'a.order_id' => $order_id,
            'a.merchant_id' => $merchant_id,
        ];
        $order = Db::name('shop_order')->alias('a')
            ->field('a.*, b.username as u_username, b.nickname as u_nickname, b.email as u_email, b.mobile as u_mobile')
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->find();
        // 收货地址处理
        $order['province'] = get_province_name($order['province']);
        $order['city']     = get_city_name($order['city']);
        $order['district'] = get_area_name($order['district']);
        $order['prom_type_virtual'] = false;

        // 查询订单附属信息条件
        $where = [
            'order_id' => $order_id,
        ];

        // 订单记录处理
        $orderLog = Db::name('shop_order_log')->where($where)->order('action_id desc')->select();
        foreach ($orderLog as $key => $value) {
            $orderLog[$key]['action_desc'] = str_replace("！", "", $value['action_desc']);
            if (0 == $value['action_user']) {
                // 若action_user为0，表示会员操作，根据订单号中的ID获取会员名。
                if (intval($order['users_id']) === intval($value['users_id'])) {
                    // 会员操作
                    $orderLog[$key]['username'] = '会 &nbsp; 员: '.$order['u_username'];
                } else {
                    // 商家操作
                    $orderLog[$key]['username'] = '商 &nbsp; 家: '. Db::name('users')->where('users_id', $value['users_id'])->getField('username');
                }
            } else {
                // 若action_user不为0，表示管理员操作，根据ID获取管理员名。
                $user_name = Db::name('admin')->field('user_name')->where('admin_id', $value['action_user'])->find();
                $orderLog[$key]['username'] = '管理员: '.$user_name['user_name'];
            }
            // 操作时，订单发货状态
            $orderLog[$key]['express_status'] = 1 == $value['express_status'] ? '已发货' : '未发货';
            // 操作时，订单付款状态
            $orderLog[$key]['pay_status'] = 1 == $value['pay_status'] ? '已支付' : '未支付';
        }

        // 处理订单详细表数据处理
        $orderDetails = Db::name('shop_order_details')->where($where)->select();
        foreach ($orderDetails as $key => $value) {
            // 包含虚拟产品
            if ($value['prom_type'] == 1) $order['prom_type_virtual'] = true;
            // 产品属性处理
            $ValueData = unserialize($value['data']);
            // 规制值
            $spec_value = !empty($ValueData['spec_value']) ? htmlspecialchars_decode($ValueData['spec_value']) : '';
            $spec_value = htmlspecialchars_decode($spec_value);
            // 旧参数
            $attr_value = !empty($ValueData['attr_value']) ? htmlspecialchars_decode($ValueData['attr_value']) : '';
            $attr_value = htmlspecialchars_decode($attr_value);
            // 新参数
            $attr_value_new = !empty($ValueData['attr_value_new']) ? htmlspecialchars_decode($ValueData['attr_value_new']) : '';
            $attr_value_new = htmlspecialchars_decode($attr_value_new);
            // 优先显示新参数
            $attr_value = !empty($attr_value_new) ? $attr_value_new : $attr_value;
            $orderDetails[$key]['data'] = $spec_value . $attr_value;
            // 产品内页地址
            $orderDetails[$key]['arcurl'] = '';// get_arcurl($array_new[$value['product_id']]);
            // 小计
            $orderDetails[$key]['subtotal'] = $value['product_price'] * $value['num'];
            // 支持子目录
            $orderDetails[$key]['litpic'] = handle_subdir_pic($orderDetails[$key]['litpic']);
        }

        // 订单类型
        $order['prom_type_name'] = empty($order['prom_type']) ? '普通订单' : '虚拟订单';

        // 查询物流链接
        $orderExpress = "https://www.kuaidi100.com/chaxun?com=".$order['express_code']."&nu=".$order['express_order'];

        // 订单状态
        $orderStatusArr = Config::get('global.admin_order_status_arr');

        // 支付方式
        if (!empty($order['pay_name'])) {
            $payMethodArr = Config::get('global.pay_method_arr');
            $order['pay_name'] = !empty($payMethodArr[$order['pay_name']]) ? $payMethodArr[$order['pay_name']] : '未知方式：' . $order['pay_name'];
        } else {
            $order['pay_name'] = '未支付';
        }

        return [
            'order' => $order,
            'orderLog' => $orderLog,
            'orderDetails' => $orderDetails,
            'orderExpress' => $orderExpress,
            'orderStatusArr' => $orderStatusArr,
        ];
    }

    // 关闭商家订单
    public function closeMerchantOrder($merchant_id = 0, $order_id = 0)
    {
        $where = [
            'order_id' => $order_id,
            'merchant_id' => $merchant_id
        ];
        $update = [
            'order_status' => -1,
            'update_time' => getTime()
        ];
        $updateID = Db::name('shop_order')->where($where)->update($update);
        if (!empty($updateID)) {
            return true;
        } else {
            return false;
        }
    }

    // 确认商家订单收货
    public function confirmMerchantOrder($merchant_id = 0, $order_id = 0)
    {
        $where = [
            'order_id' => $order_id,
            'merchant_id' => $merchant_id
        ];
        $update = [
            'order_status' => 3,
            'update_time' => getTime()
        ];
        $updateID = Db::name('shop_order')->where($where)->update($update);
        if (!empty($updateID)) {
            return true;
        } else {
            return false;
        }
    }

    // 商家订单发货
    public function sendMerchantOrder($merchant_id = 0, $post = [])
    {
        // 更新信息
        $update = [
            'order_status'  => 2,
            'express_order' => strval($post['express_order']),
            'express_name'  => strval($post['express_name']),
            'express_code'  => strval($post['express_code']),
            'express_time'  => getTime(),
            'consignee'     => strval($post['consignee']),
            'update_time'   => getTime(),
            'virtual_delivery' => $post['virtual_delivery'],
        ];

        // 查询是否已提交过发货
        $where = [
            'order_id' => intval($post['order_id']),
            'express_status' => 1,
        ];
        $countID = Db::name('shop_order_log')->where($where)->count();

        // 更新订单为已发货
        $where = [
            'order_id' => intval($post['order_id']),
            'users_id' => intval($post['users_id']),
        ];
        if (!empty($countID)) {
            $promType = Db::name('shop_order')->where($where)->getField('prom_type');
            $action_desc = '修改发货内容';
            if (1 == $post['prom_type']) {
                // 提交的数据为虚拟订单
                $action_note = intval($promType) != intval($post['prom_type']) ? '商家将普通订单修改为虚拟订单。' : '虚拟订单，无需物流。';
                // 若存在数据则拼装
                if (!empty($post['virtual_delivery'])) $action_note .= '给买家回复：'.$post['virtual_delivery'];
            } else {
                // 提交的数据为普通订单
                $action_note = intval($promType) != intval($post['prom_type']) ? '商家将虚拟订单修改为普通订单。' : '商家使用' . $post['express_name'] . '发货成功';
                // 若存在数据则拼装
                if (!empty($post['virtual_delivery'])) $action_note .= '给买家回复：'.$post['virtual_delivery'];
            }
            $update['prom_type'] = intval($post['prom_type']);
        } else {
            // 初次发货，拼装发货内容
            $action_desc = '发货成功';
            $action_note = '商家使用' . $post['express_name'] . '发货成功';
            if (1 === intval($post['prom_type'])) {
                // 若为虚拟订单，无需发货物流。
                $action_note = '虚拟订单，无需物流。';
                // 若存在数据则拼装
                if (!empty($post['virtual_delivery'])) $action_note .= '商家给买家回复：' . $post['virtual_delivery'];
            }
            $update['prom_type'] = intval($post['prom_type']);
        }
        $updateID = Db::name('shop_order')->where($where)->update($update);
        if (!empty($updateID)) {
            $update['action_desc'] = $action_desc;
            $update['action_note'] = $action_note;
            return $update;
        } else {
            return false;
        }
    }

    // 获取商家售后订单列表
    public function getMerchantServiceList($merchant_id = 0)
    {
        // 查询条件
        $where = [
            'a.merchant_id' => $merchant_id
        ];

        // 返回参数
        $param = [];

        // 订单号查询
        $param['keywords'] = input('keywords/s', '');
        if (!empty($param['keywords'])) $where['a.order_code|a.product_name|a.refund_code'] = ['LIKE', "%{$param['keywords']}%"];

        // 支付方式查询
        $param['pay_name'] = input('pay_name/s', '');
        if (!empty($param['pay_name'])) $where['c.pay_name'] = $param['pay_name'];

        // 订单下单终端查询
        $param['order_terminal'] = input('order_terminal/d', 0);
        if (!empty($param['order_terminal'])) $where['c.order_terminal'] = $param['order_terminal'];

        // 发布时间查询
        $param['add_time'] = input('add_time/s', '');
        if (!empty($param['add_time'])) {
            $add_time = explode('~', $param['add_time']);
            $begin = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]));
            $where['a.add_time'] = ['between', "$begin, $finish"];
        }

        // 分页查询
        $count = Db::name('shop_order_service')->alias('a')
            ->join('__SHOP_ORDER_DETAILS__ b', 'a.details_id = b.details_id', 'LEFT')
            ->join('__SHOP_ORDER__ c', 'a.order_id = c.order_id', 'LEFT')
            ->where($where)
            ->count('a.service_id');
        $pageObj = new Page($count, config('paginate.list_rows'));

        // 数据查询
        $list = Db::name('shop_order_service')->alias('a')
            ->field('a.*, b.product_price, b.num')
            ->join('__SHOP_ORDER_DETAILS__ b', 'a.details_id = b.details_id', 'LEFT')
            ->join('__SHOP_ORDER__ c', 'a.order_id = c.order_id', 'LEFT')
            ->where($where)
            ->order('a.order_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();

        $archivesList = get_archives_data($list, 'product_id');
        $ServiceStatus = Config::get('global.order_service_status');
        foreach ($list as $key => $value) {
            // 添加时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);
            // 商品封面图
            $value['product_img'] = handle_subdir_pic(get_default_pic($value['product_img']));
            // 商品前台URL
            $value['viewProductUrl'] = urldecode(arcurl('home/Product/view', $archivesList[$value['product_id']]));
            // 商品规格，组合数据
            $value['product_spec'] = explode('&lt;br/&gt;', $value['product_spec']);
            $valueData = '';
            foreach ($value['product_spec'] as $key_1 => $value_1) {
                if (!empty($value_1)) $valueData .= '<span>' . trim(explode('：', $value_1)[1]) . '</span>';
            }
            $value['product_spec'] = $valueData;
            // 计算退还金额
            if (1 == $value['service_type']) {
                $value['ShippingFee'] = $value['refund_price'] = '0.00';
            } else if (2 == $value['service_type']) {
                // 运费计算
                $ShippingFee = 0;
                $value['ShippingFee'] = $ShippingFee;
                // 计算退还金额
                $ProductPrice = 0;
                if (!empty($value['product_price'])) {
                    $ProductPrice = sprintf("%.2f", ($value['product_price'] * (string)$value['num']) - (string)$ShippingFee);
                    $value['refund_price'] = $ProductPrice;
                }
            }
            // 售后订单状态
            $value['statusName'] = !empty($ServiceStatus[$value['status']]) ? $ServiceStatus[$value['status']] : '订单异常';

            $list[$key] = $value;
        }

        // 分页显示输出
        $pageStr = $pageObj->show();
        // 是否安装 可视化微信小程序（商城版） ，未安装开启则不显示小程序支付
        $where = [
            'status' => 1,
            'code' => 'DiyminiproMall'
        ];
        $openMall = Db::name('weapp')->where($where)->count();

        // 返回加载页面信息
        return [
            'list' => $list,
            'param' => $param,
            'page' => $pageStr,
            'pager' => $pageObj,
            'openMall' => $openMall,
        ];
    }

    // 获取商家售后订单详情
    public function getMerchantServiceDetails($merchant_id = 0, $service_id = 0)
    {
        // 退换货信息
        $where = [
            'service_id' => $service_id,
            'merchant_id' => $merchant_id,
        ];
        $Service[0] = Db::name('shop_order_service')->where($where)->find();
        $archivesList = get_archives_data($Service, 'product_id');
        $Service = $Service[0];

        // 数据处理
        $Service['viewProductUrl'] = urldecode(arcurl('home/Product/view', $archivesList[$Service['product_id']]));
        $Service['StatusName'] = Config::get('global.order_service_status')[$Service['status']];
        $Service['upload_img'] = !empty($Service['upload_img']) ? explode(',', $Service['upload_img']) : [];
        array_pop($Service['upload_img']);
        $Service['product_img'] = handle_subdir_pic(get_default_pic($Service['product_img']));
        $Service['product_spec'] = str_replace("&lt;br/&gt;", " || ", $Service['product_spec']);
        $Service['product_spec'] = trim($Service['product_spec']);
        $Service['product_spec'] = rtrim($Service['product_spec'], '||');
        $Service['TypeName'] = Config::get('global.order_service_type')[$Service['service_type']];
        $Service['users_delivery'] = !empty($Service['users_delivery']) ? unserialize($Service['users_delivery']) : '';
        $Service['admin_delivery'] = !empty($Service['admin_delivery']) ? unserialize($Service['admin_delivery']) : '';
        $Service['product_num'] = (string)$Service['product_num'];

        // 用户发货后计算退还金额、余额
        if (5 == $Service['status'] || 7 == $Service['status'] || 2 == $Service['service_type']) {
            // 查询订单数据
            $where = [
                'b.order_id' => $Service['order_id'],
                'b.details_id' => $Service['details_id'],
                'b.apply_service' => 1
            ];
            $Order = Db::name('shop_order')->field('a.*, b.*')
                ->alias('a')
                ->where($where)
                ->join('__SHOP_ORDER_DETAILS__ b', 'a.order_id = b.order_id', 'LEFT')
                ->find();
            $Order['order_total_num'] = (string)$Order['order_total_num'];

            // 运费计算
            $ShippingFee = 0;
            $Service['ShippingFee'] = $ShippingFee;
            // if (!empty($Order['shipping_fee'])) {
            //     $ShippingFee = sprintf("%.2f", ($Order['shipping_fee'] / $Order['order_total_num']) * $Service['product_num']);
            //     $Service['ShippingFee'] = $ShippingFee;
            // }

            // 退回应付款
            $ProductPrice = 0;
            if (!empty($Order['product_price'])) {
                $ProductPrice = sprintf("%.2f", ($Order['product_price'] * $Service['product_num']) - $ShippingFee);
                $Service['refund_price'] = $ProductPrice;
            }
        } else {
            $Service['refund_price'] = '0.00';
        }

        // 会员信息
        $serviceUsers = Db::name('users')->field('users_id, username, nickname, mobile')->find($Service['users_id']);
        $serviceUsers['nickname'] = empty($serviceUsers['nickname']) ? $serviceUsers['username'] : $serviceUsers['nickname'];

        // 服务记录表信息
        $serviceLog = Db::name('shop_order_service_log')->order('log_id desc')->where('service_id', $Service['service_id'])->select();
        foreach ($serviceLog as $key => $value) {
            if (!empty($value['users_id'])) {
                if (intval($value['users_id']) === intval($Service['users_id'])) {
                    $serviceLog[$key]['name'] = '会员：'.$serviceUsers['nickname'];
                } else {
                    // 商家操作
                    $serviceLog[$key]['name'] = '商家：'.Db::name('users')->where('users_id', $value['users_id'])->getField('username');
                }
            } else if (!empty($value['admin_id'])) {
                $serviceLog[$key]['name'] = '商家：'.getAdminInfo(session('admin_id'))['user_name'];
            }
        }

        $result = [
            'service' => $Service,
            'serviceLog' => $serviceLog,
            'serviceUsers' => $serviceUsers,
        ];
        return $result;
    }

    // -------- 商品部分
    // 获取商家商品详情
    public function getMerchantProductDetails($merchant_id = 0, $aid = 0)
    {
        // 查询商品条件
        $where = [
            'a.aid' => $aid,
            'a.merchant_id' => $merchant_id
        ];
        // 查询商品字段
        $field = 'a.*, b.content, c.netdisk_url, c.netdisk_pwd, c.unzip_pwd, c.text_content';
        // 执行商品查询
        $archives = Db::name('archives')->alias('a')
            ->where($where)
            ->field($field)
            ->join('__PRODUCT_CONTENT__ b', 'a.aid = b.aid', 'LEFT')
            ->join('__PRODUCT_NETDISK__ c', 'a.aid = c.aid', 'LEFT')
            ->find();
        if (empty($archives)) return false;

        $archives['litpic'] = handle_subdir_pic(get_default_pic($archives['litpic']));
        $archives['content'] = !empty($archives['content']) ? htmlspecialchars_decode($archives['content']) : '';
        return $archives;
    }

    // 获取商家商品列表
    public function getMerchantProductList($merchant_id = 0, $param = [])
    {
        // 查询条件
        $where = [
            'is_del' => 0,
            'merchant_id' => $merchant_id
        ];

        // 状态查询
        if (!empty($param['query']) && 1 === intval($param['query'])) {
            $where['status'] = 1;
        } else if (!empty($param['query']) && 2 === intval($param['query'])) {
            $where['status'] = 0;
        } else if (!empty($param['query']) && 3 === intval($param['query'])) {
            $where['stock_count'] = 0;
        } else if (!empty($param['query']) && 4 === intval($param['query'])) {
            $where['arcrank'] = -1;
        }

        // 商品名称查询
        if (!empty($param['title'])) $where['title'] = ['LIKE', "%{$param['title']}%"];

        // 商品类型查询
        if (!empty($param['prom_type'])) $where['prom_type'] = 'shi' === strval($param['prom_type']) ? 0 : 1;

        // 商品栏目查询
        if (!empty($param['typeid'])) $where['typeid'] = intval($param['typeid']);

        // 发布时间查询
        if (!empty($param['add_time'])) {
            $add_time = explode('~', $param['add_time']);
            $begin = strtotime(rtrim($add_time[0]));
            $finish = strtotime(rtrim($add_time[1]));
            $where['add_time'] = ['between', "$begin, $finish"];
        }

        // 执行查询
        $count = Db::name('archives')->where($where)->count('aid');
        $page = new Page($count, config('paginate.list_rows'));
        $list = Db::name('archives')->where($where)->limit($page->firstRow.','.$page->listRows)->order('sort_order asc, aid desc')->select();
        $archivesList = get_archives_data($list, 'aid');
        foreach ($list as $key => $value) {
            // 商品编辑页URL
            $value['editProductUrl'] = url('plugins/MultiMerchant/product_edit', ['aid'=>$value['aid']]);
            // 商品详情URL
            $value['viewProductUrl'] = urldecode(arcurl('home/View/index', $archivesList[$value['aid']]));
            // 商品图片
            $value['litpic'] = handle_subdir_pic(get_default_pic($value['litpic']));
            // 销售状态
            $value['statusName'] = !empty($value['status']) ? '销售中' : '仓库中';
            // 审核状态
            $value['arcrankName'] = $value['arcrank'] == -1 ? '待审核' : '已审核';
            $list[$key] = $value;
        }

        $productAssign['list'] = $list;
        $productAssign['page'] = $page->show();
        $productAssign['pager'] = $page;
        return $productAssign;
    }

    // 商家商品添加
    public function addMerchantProduct($merchant_id = 0, $post = [], $users = [])
    {
        // 商品添加数据
        $time = getTime();
        $insert = [
            'typeid'          => !empty($post['typeid']) ? intval($post['typeid']) : 0,
            'channel'         => 2,
            'title'           => !empty($post['title']) ? strval($post['title']) : '',
            'litpic'          => !empty($post['litpic']) ? strval($post['litpic']) : '',
            'is_litpic'       => !empty($post['litpic']) ? 1 : 0,
            'origin'          => '商家商品',
            'arcrank'         => -1,
            'seo_description' => strval($post['seo_description']),
            'users_id'        => intval($users['users_id']),
            'author'          => strval($users['username']),
            'merchant_id'     => intval($merchant_id),
            'free_shipping'   => !empty($post['free_shipping']) ? intval($post['free_shipping']) : 0,
            'users_price'     => !empty($post['users_price']) ? floatval($post['users_price']) : 0,
            'stock_count'     => !empty($post['stock_count']) ? intval($post['stock_count']) : 0,
            'stock_show'      => !empty($post['stock_show']) ? intval($post['stock_show']) : 0,
            'prom_type'       => !empty($post['prom_type']) ? intval($post['prom_type_vir']) : 0,
            'status'          => 0,
            'sort_order'      => 100,
            'add_time'        => $time,
            'update_time'     => $time
        ];
        $insertID = Db::name('archives')->insertGetId($insert);
        // 返回结果
        if (!empty($insertID)) {
            return $insertID;
        } else {
            return false;
        }
    }

    // 商家商品编辑
    public function editMerchantProduct($merchant_id = 0, $post = [])
    {
        // 商品编辑数据
        $where = [
            'aid' => $post['aid'],
            'merchant_id' => $merchant_id,
        ];
        $time = getTime();
        $update = [
            'typeid'          => !empty($post['typeid']) ? intval($post['typeid']) : 0,
            'channel'         => 2,
            'title'           => !empty($post['title']) ? strval($post['title']) : '',
            'litpic'          => !empty($post['litpic']) ? strval($post['litpic']) : '',
            'is_litpic'       => !empty($post['litpic']) ? 1 : 0,
            'arcrank'         => -1,
            'seo_description' => strval($post['seo_description']),
            'merchant_id'     => intval($merchant_id),
            'free_shipping'   => !empty($post['free_shipping']) ? intval($post['free_shipping']) : 0,
            'users_price'     => !empty($post['users_price']) ? floatval($post['users_price']) : 0,
            'stock_count'     => !empty($post['stock_count']) ? intval($post['stock_count']) : 0,
            'stock_show'      => !empty($post['stock_show']) ? intval($post['stock_show']) : 0,
            'prom_type'       => !empty($post['prom_type']) ? intval($post['prom_type_vir']) : 0,
            'update_time'     => $time
        ];
        $updateID = Db::name('archives')->where($where)->update($update);
        // 返回结果
        if (!empty($updateID)) {
            return $post['aid'];
        } else {
            return false;
        }
    }

    // 添加商品详情内容
    public function addMerchantProductContent($aid = 0, $productContent = '')
    {
        $insert = [
            'aid' => intval($aid),
            'content' => htmlspecialchars($productContent),
            'add_time' => getTime(),
            'update_time' => getTime(),
        ];
        Db::name('product_content')->insert($insert);
    }

    // 编辑商品详情内容
    public function editMerchantProductContent($aid = 0, $productContent = '')
    {
        $where = [
            'aid' => $aid,
        ];
        $update = [
            'content' => htmlspecialchars($productContent),
            'update_time' => getTime(),
        ];
        Db::name('product_content')->where($where)->update($update);
    }

    // 添加商品图片
    public function addMerchantProductImg($aid = 0, $productImg = [], $productTitle = '')
    {
        if (!empty($productImg) && count($productImg) > 1) {
            // 弹出最后一个
            array_pop($productImg);
            // 删除产品图片
            Db::name('product_img')->where(['aid' => ['IN', $aid]])->delete();
            // 添加图片
            $insertAll = array();
            $sort_order = 0;
            foreach($productImg as $key => $val) {
                if($val == null || empty($val))  continue;
                
                $img_info = [];
                $filesize = 0;
                if (is_http_url($val)) {
                    $imgurl = handle_subdir_pic($val);
                } else {
                    $imgurl = ROOT_PATH . ltrim($val, '/');
                    $filesize = @filesize('.'.$val);
                }
                $img_info = @getimagesize($imgurl);
                $width = isset($img_info[0]) ? $img_info[0] : 0;
                $height = isset($img_info[1]) ? $img_info[1] : 0;
                $type = isset($img_info[2]) ? $img_info[2] : 0;
                $attr = isset($img_info[3]) ? $img_info[3] : '';
                $mime = isset($img_info['mime']) ? $img_info['mime'] : '';
                $intro = !empty($imgintro[$key]) ? $imgintro[$key] : '';
                ++$sort_order;
                $insertAll[] = array(
                    'aid' => $aid,
                    'title' => $productTitle,
                    'image_url' => $val,
                    'intro' => $intro,
                    'width' => $width,
                    'height' => $height,
                    'filesize' => $filesize,
                    'mime' => $mime,
                    'sort_order' => $sort_order,
                    'add_time' => getTime(),
                );
            }
            if (!empty($insertAll)) Db::name('product_img')->insertAll($insertAll);

            // 删除缩略图
            delFile(UPLOAD_PATH."product/thumb/$aid");
        }
    }

    // 批量添加产品规格名称、规格值、规格价格库存
    public function bulkaddMerchantProductSpec($merchant_id = 0, $aid = 0, $post = [])
    {
        // 规格信息处理
        $merchantSpecArray = session($merchant_id . '_MerchantSpecArray');
        $preset_ids = $preset_mark_ids = [];
        foreach ($merchantSpecArray as $key => $value) {
            // 获取规格名ID追加
            if (!empty($key)) array_push($preset_mark_ids, $key);
            // 获取规格值ID追加
            foreach ($value as $subValue) {
                if (!empty($subValue)) array_push($preset_ids, $subValue);
            }
        }
        if (!empty($merchant_id) && !empty($aid) && !empty($preset_ids)) {
            // 查询预设的规格的规格值数据
            $PresetData = $this->getProductSpecPresetValue($merchant_id, $preset_mark_ids, 'IN');

            // 规格标记ID
            $specMarkID = $this->getMaxSpecMarkID('product_spec_data');

            // 产品规格名称及规格值
            $time = getTime();
            $insertAll = [];
            foreach ($PresetData as $key => $value) {
                $insertAll[$key] = [
                    'aid'           => $aid,
                    'spec_mark_id'  => intval($specMarkID) + intval($value['preset_mark_id']),
                    'spec_name'     => $value['preset_name'],
                    'spec_value'    => $value['preset_value'],
                    'spec_value_id' => $value['preset_id'],
                    'spec_is_select'=> 0,
                    'add_time'      => $time,
                    'update_time'   => $time,
                ];
                if (in_array($value['preset_id'], $preset_ids)) $insertAll[$key]['spec_is_select'] = 1;
            }
            Db::name('product_spec_data')->insertAll($insertAll);

            // 产品规格价格及规格库存
            $insertAll = [];
            foreach ($post['preset_price'] as $key_1 => $value_1) {
                $insertAll[] = [
                    'aid'           => $aid,
                    'spec_value_id' => $key_1,
                    'spec_price'    => $value_1['users_price'],
                    'spec_stock'    => $post['preset_stock'][$key_1]['stock_count'],
                    'spec_sales_num'=> $post['preset_sales'][$key_1]['spec_sales_num'],
                    'add_time'      => $time,
                    'update_time'   => $time,
                ];
            }
            Db::name('product_spec_value')->insertAll($insertAll);
        }
    }

    // 批量编辑商品规格
    public function bulkeditMerchantProductSpec($merchant_id = 0, $aid = 0, $post = [])
    {
        if (!empty($merchant_id) && !empty($aid)) {
            // 查询商品规格处理库的规格信息
            $insertAll = $this->listProductSpecDataHandle($aid);
            // 产品规格名称及规格值
            foreach ($insertAll as $key => $value) {
                unset($insertAll[$key]['spec_id']);
            }
            if (!empty($insertAll)) {
                // 删除商品规格数据
                Db::name('product_spec_data')->where(['aid'=>$aid])->delete(true);
                // 新增商品规格数据
                Db::name('product_spec_data')->insertAll($insertAll);
                // 删除商品规格处理库的规格信息
                $this->clearProductSpecDataHandle($aid);
            }
            // 产品规格价格及规格库存
            $insertAll = [];
            $time = getTime();
            foreach ($post['spec_price'] as $key_1 => $value_1) {
                $insertAll[] = [
                    'aid'           => $aid,
                    'spec_value_id' => $key_1,
                    'spec_price'    => $value_1['users_price'],
                    'spec_stock'    => $post['spec_stock'][$key_1]['stock_count'],
                    'spec_sales_num'=> $post['spec_sales'][$key_1]['spec_sales_num'],
                    'add_time'      => $time,
                    'update_time'   => $time,
                ];
            }
            if (!empty($insertAll)) {
                // 删除商品规格价格数据
                Db::name('product_spec_value')->where(['aid'=>$aid])->delete(true);
                // 新增商品规格价格数据
                Db::name('product_spec_value')->insertAll($insertAll);
            }
        }
    }

    // 添加虚拟商品信息
    public function addMerchantProductNetdisk($aid = 0, $post = [])
    {
        $count = Db::name('product_netdisk')->where('aid', $aid)->count();
        $data  = [
            'aid'          => $aid,
            'netdisk_url'  => !empty($post['netdisk_url']) ? $post['netdisk_url'] : '',
            'netdisk_pwd'  => !empty($post['netdisk_pwd']) ? $post['netdisk_pwd'] : '',
            'unzip_pwd'    => !empty($post['unzip_pwd']) ? $post['unzip_pwd'] : '',
            'text_content' => !empty($post['text_content']) ? $post['text_content'] : '',
            'add_time'     => getTime(),
            'update_time'  => getTime(),
        ];
        Db::name('product_netdisk')->insert($data);
    }

    // 编辑虚拟商品信息
    public function editMerchantProductNetdisk($aid = 0, $post = [])
    {
        $where = [
            'aid' => $aid,
        ];
        $data  = [
            'netdisk_url'  => !empty($post['netdisk_url']) ? $post['netdisk_url'] : '',
            'netdisk_pwd'  => !empty($post['netdisk_pwd']) ? $post['netdisk_pwd'] : '',
            'unzip_pwd'    => !empty($post['unzip_pwd']) ? $post['unzip_pwd'] : '',
            'text_content' => !empty($post['text_content']) ? $post['text_content'] : '',
            'update_time'  => getTime()
        ];
        Db::name('product_netdisk')->where($where)->update($data);
    }

    // 添加商品参数
    public function addMerchantProductCustomParam($aid = 0, $paramName = [], $paramValue = [])
    {
        // 强制删除商品参数
        $where = [
            'aid' => $aid,
        ];
        Db::name('product_custom_param')->where($where)->delete(true);

        // 新增商品参数
        if (!empty($paramName) && !empty($paramValue)) {
            $insertAll = [];
            $time = getTime();
            foreach ($paramName as $key => $value) {
                if (!empty($value) && !empty($paramValue[$key])) {
                    $insertAll[] = [
                        'aid' => $aid,
                        'param_name' => $value,
                        'param_value' => $paramValue[$key],
                        'sort_order' => $key,
                        'add_time' => $time,
                        'update_time' => $time,
                    ];
                }
            }
            if (!empty($insertAll)) Db::name('product_custom_param')->insertAll($insertAll);
        }
    }

    // 读取规格预设库最大参数标记ID
    public function getMaxPresetMarkID()
    {
        // 查询最大标记ID并+1后返回
        $maxPresetMarkID = Db::name('product_spec_preset')->order('preset_mark_id desc')->getField('preset_mark_id');
        $maxPresetMarkID++;
        return $maxPresetMarkID;
    }

    // 查询预设的规格数据
    public function getProductSpecPreset($merchant_id = 0, $usePresetMarkID = '', $option = '')
    {
        // 查询处理
        $where = [
            'merchant_id' => ['IN', [0, $merchant_id]],
        ];
        // 如果存在预设规格标记ID和查询表达式则执行
        if (!empty($usePresetMarkID) && !empty($option)) {
            $usePresetMarkID = is_array($usePresetMarkID) ? $usePresetMarkID : explode(',', $usePresetMarkID);
            $where['preset_mark_id'] = [$option, $usePresetMarkID];
        }
        $field = 'preset_id, preset_mark_id, preset_name, merchant_id';
        $order = 'merchant_id asc, preset_mark_id desc';

        // 执行查询
        $Preset = Db::name('product_spec_preset')->where($where)->field($field)->group('preset_mark_id')->order($order)->select();

        // 返回数据
        return $Preset;
    }

    // 查询预设的规格的规格值数据
    public function getProductSpecPresetValue($merchant_id = 0, $usePresetMarkID = '', $option1 = '', $presetID = [], $option2 = '')
    {
        // 查询处理
        $where = [
            'merchant_id' => ['IN', [0, $merchant_id]],
        ];
        // 如果存在预设规格标记ID和查询表达式则执行
        if (!empty($usePresetMarkID) && !empty($option1)) {
            $usePresetMarkID = is_array($usePresetMarkID) ? $usePresetMarkID : explode(',', $usePresetMarkID);
            $where['preset_mark_id'] = [$option1, $usePresetMarkID];
        }
        if (!empty($presetID) && !empty($option2)) {
            $presetID = is_array($presetID) ? $presetID : explode(',', $presetID);
            $where['preset_id'] = [$option2, $presetID];
        }
        $field = 'preset_id, preset_mark_id, preset_name, preset_value, merchant_id';
        $order = 'merchant_id asc, preset_mark_id desc';

        // 执行查询
        $Preset = Db::name('product_spec_preset')->where($where)->field($field)->order($order)->select();

        // 返回数据
        return $Preset;
    }

    // 剔除已选择的规格值查询未选择的规格值数据
    public function getNotInProductSpecPresetValue($merchant_id = 0, $presetIDArray = [], $post = [])
    {
        // 查询其他未选择规格值
        $where = [
            'preset_mark_id' => $post['presetMarkID'],
            'preset_id' => ['NOT IN', $presetIDArray],
            'merchant_id' => ['IN', [0, $merchant_id]],
        ];
        $specResult['option'] = Db::name('product_spec_preset')->where($where)->select();

        // 查询当选的规格值
        $specResult['value']  = Db::name('product_spec_preset')->where('preset_id', $post['presetID'])->getField('preset_value');

        // 返回数据
        return $specResult;
    }

    // 读取商品规格库最大规格标记ID
    public function getMaxSpecMarkID($table = 'product_spec_data', $field = 'spec_mark_id')
    {
        // 查询最大标记ID并+1后返回
        $maxSpecMarkID = Db::name($table)->order($field . ' desc')->getField($field);
        $maxSpecMarkID++;
        return $maxSpecMarkID;
    }

    // 查询商品规格库指定规格组下的所有规格值信息
    public function getProductSpecDataValue($aid = 0, $specMarkID = 0, $option = 'IN')
    {
        // 查询处理
        $where = [
            'aid' => $aid,
        ];
        // 如果存在预设规格标记ID和查询表达式则执行
        if (!empty($specMarkID) && !empty($option)) {
            $specMarkID = is_array($specMarkID) ? $specMarkID : explode(',', $specMarkID);
            $where['spec_mark_id'] = [$option, $specMarkID];
        }
        $order = 'spec_mark_id asc, spec_id asc, spec_value_id asc';
        // 执行查询
        $specData = Db::name('product_spec_data')->where($where)->order($order)->select();

        // 返回数据
        return $specData;
    }

    // 清除商品规格表的规格信息
    public function clearProductSpecData($aid = 0, $specMarkID = 0, $valueID = 0)
    {
        $where = [
            'aid' => $aid,
        ];
        if (!empty($specMarkID)) $where['spec_mark_id'] = $specMarkID;
        if (!empty($valueID)) $where['spec_value_id'] = $valueID;
        // 执行删除
        $isResult = Db::name('product_spec_data')->where($where)->delete(true);
        if (!empty($isResult)) {
            return true;
        } else {
            return false;
        }
    }

    // 清除商品规格价格表的规格信息
    public function clearProductSpecValue($aid = 0)
    {
        $where = [
            'aid' => $aid,
        ];
        // 执行删除
        $isResult = Db::name('product_spec_value')->where($where)->delete(true);
        if (!empty($isResult)) {
            return true;
        } else {
            return false;
        }
    }

    // 查询商品规格处理表的规格全部信息(列表形式)
    // 注：此数据表主要用于商品编辑时对规格进行处理，若商品进行保存则此表数据覆盖product_spec_data数据库
    public function listProductSpecDataHandle($aid = 0, $specMarkID = '', $select = 0)
    {
        // 规格查询
        $where = [
            'aid' => $aid,
        ];
        if (!empty($select)) $where['spec_is_select'] = 1;
        if (!empty($specMarkID)) {
            $specMarkID = is_array($specMarkID) ? $specMarkID : explode(',', $specMarkID);
            $where['spec_mark_id'] = ['IN', $specMarkID];
        }
        $order = 'spec_mark_id asc, spec_value_id asc';
        $result = Db::name('product_spec_data_handle')->where($where)->order($order)->select();
        return $result;
    }

    // 查询商品规格处理表的规格信息(仅ID信息，二维数组形式)
    // 注：此数据表主要用于商品编辑时对规格进行处理，若商品进行保存则此表数据覆盖product_spec_data数据库
    public function getProductSpecDataHandle($aid = 0, $specMarkID = '', $select = 1)
    {
        // 规格查询
        $where = [
            'aid' => $aid,
            'spec_is_select' => 1,
        ];
        if (empty($select)) unset($where['spec_is_select']);
        if (!empty($specMarkID)) {
            $specMarkID = is_array($specMarkID) ? $specMarkID : explode(',', $specMarkID);
            $where['spec_mark_id'] = ['IN', $specMarkID];
        }
        $order = 'spec_value_id asc, spec_id asc, spec_mark_id asc';
        $data = Db::name('product_spec_data_handle')->field('spec_mark_id, spec_value_id')->where($where)->order($order)->select();
        $result = [];
        if (!empty($data)) {
            foreach ($data as $key => $value) {
                $result[$value['spec_mark_id']][] = $value['spec_value_id'];
            }
        }
        return $result;
    }

    // 添加商品规格处理表的规格信息
    // 注：此数据表主要用于商品编辑时对规格进行处理，若商品进行保存则此表数据覆盖product_spec_data数据库
    public function addProductSpecDataHandle($data = [], $post = [])
    {
        if (!empty($post)) {
            // 执行更新
            $where = [
                'aid' => $post['aid'],
                'spec_value_id' => $post['valueID'],
                'spec_mark_id' => $post['specMarkID'],
            ];
            $update = [
                'spec_is_select' => 1,
                'update_time' => getTime()
            ];
            $isResult = Db::name('product_spec_data_handle')->where($where)->update($update);
        } else {
            // 执行添加
            $isResult = Db::name('product_spec_data_handle')->insertAll($data);
        }
        if (!empty($isResult)) {
            return true;
        } else {
            return false;
        }
    }

    // 清除商品规格数据处理表的规格信息
    // 注：此数据表主要用于商品编辑时对规格进行处理，若商品进行保存则此表数据覆盖product_spec_data数据库
    public function clearProductSpecDataHandle($aid = 0, $specMarkID = 0, $valueID = 0)
    {
        $where = [
            'aid' => $aid,
        ];
        if (!empty($specMarkID)) $where['spec_mark_id'] = $specMarkID;
        if (!empty($valueID)) {
            // 执行更新
            $where['spec_value_id'] = $valueID;
            $update = [
                'spec_is_select' => 0,
                'update_time' => getTime()
            ];
            $isResult = Db::name('product_spec_data_handle')->where($where)->update($update);
        } else {
            // 执行删除
            $isResult = Db::name('product_spec_data_handle')->where($where)->delete(true);
        }
        if (!empty($isResult)) {
            return true;
        } else {
            return false;
        }
    }


    // -------- 资产详情部分
    // 资产概况
    public function getMerchantAssetOverview($merchant_id = 0)
    {
        // 查询所有订单总金额
        $where = [
            'merchant_id' => $merchant_id,
            'order_status' => ['IN', [1, 2, 3]],
        ];
        $orderAmount = Db::name('shop_order')->where($where)->sum('order_amount');

        // 商品退款金额
        $where = [
            'status' => 7,
            'service_type' => 2,
            'merchant_id' => $merchant_id,
        ];
        $refundAmount = Db::name('shop_order_service')->where($where)->sum('refund_balance');

        // 返回数据
        return [
            'orderAmount' => $orderAmount,
            'refundAmount' => $refundAmount,
        ];
    }

    // 添加商家余额提现申请
    public function addMerchantAssetWithdrawApply($multiMerchant = [], $withdraw_money = 0)
    {
        // 执行添加会员提现记录
        $time = getTime();
        $insert = [
            'withdraw_code' => date('Ymd') . $time . rand(1000, 9999),
            'users_id' => intval($multiMerchant['users_id']),
            'merchant_id' => intval($multiMerchant['merchant_id']),
            'withdraw_money' => floatval($withdraw_money),
            'service_fee' => 0,
            'arrive_money' => floatval($withdraw_money),
            'settle_type' => intval($multiMerchant['settle_type']),
            'settle_data' => strval(serialize($multiMerchant['settle_data'])),
            'status' => 1,
            'reason' => '',
            'add_time' => $time,
            'update_time' => $time,
        ];
        $insertID = Db::name('weapp_multi_merchant_withdraw')->insert($insert);
        if (!empty($insertID)) {
            // 扣除商家可提现余额，增加提现中余额
            $where = [
                'merchant_id' => $multiMerchant['merchant_id']
            ];
            $available_balance = floatval($multiMerchant['available_balance']) - floatval($withdraw_money);
            $freeze_balance = floatval($multiMerchant['freeze_balance']) + floatval($withdraw_money);
            $update = [
                'available_balance' => $available_balance,
                'freeze_balance' => $freeze_balance,
                'update_time' => getTime()
            ];
            $updateID = $this->multiMerchantDb->where($where)->update($update);
            if (!empty($updateID)) {
                return true;
            } else {
                $where = [
                    'withdraw_id' => $insertID,
                ];
                Db::name('weapp_multi_merchant_withdraw')->where($where)->delete(true);
                return false;
            }
        } else {
            return false;
        }
    }

    // 获取商家提现记录
    public function getMerchantWithdrawList($merchant_id = 0)
    {
        // 查询条件
        $where = [
            'a.merchant_id' => $merchant_id,
        ];

        // 订单号查询
        $withdraw_code = input('withdraw_code/s', '');
        if (!empty($withdraw_code)) $where['a.withdraw_code'] = ['LIKE', "%{$withdraw_code}%"];

        // 订单提现方式查询
        $settle_type = input('settle_type/d', 0);
        if (!empty($settle_type)) $where['a.settle_type'] = $settle_type;

        // 订单状态查询
        $status = input('status/d', 0);
        if (!empty($status)) $where['a.status'] = $status;

        // 分页查询
        $count = Db::name('weapp_multi_merchant_withdraw')->alias('a')->join('__WEAPP_MULTI_MERCHANT__ c', 'a.merchant_id = c.merchant_id', 'LEFT')->where($where)->count('withdraw_id');
        $pageObj = new Page($count, config('paginate.list_rows'));

        // 订单主表数据查询
        $list = Db::name('weapp_multi_merchant_withdraw')->alias('a')
            ->field('a.*, b.username as u_username, b.nickname as u_nickname, b.mobile as u_mobile, c.merchant_name')
            ->where($where)
            ->join('__USERS__ b', 'a.users_id = b.users_id', 'LEFT')
            ->join('__WEAPP_MULTI_MERCHANT__ c', 'a.merchant_id = c.merchant_id', 'LEFT')
            ->order('a.withdraw_id desc')
            ->limit($pageObj->firstRow.','.$pageObj->listRows)
            ->select();
        foreach ($list as $key => $value) {
            // 收款账户类型
            if (1 === intval($value['settle_type'])) {
                $value['settle_type_name'] = '银行卡';
            } else if (2 === intval($value['settle_type'])) {
                $value['settle_type_name'] = '支付宝';
            } else if (3 === intval($value['settle_type'])) {
                $value['settle_type_name'] = '微信';
            }

            // 收款账户内容信息
            $value['settle_data'] = !empty($value['settle_data']) ? unserialize($value['settle_data']) : [];
            if (!empty($value['settle_data'])) {
                $bankProvince = !empty($value['settle_data']['bankProvince']) ? get_province_name($value['settle_data']['bankProvince']) : '';
                $bankCity = !empty($value['settle_data']['bankCity']) ? get_city_name($value['settle_data']['bankCity']) : '';
                $bankDistrict = !empty($value['settle_data']['bankDistrict']) ? get_area_name($value['settle_data']['bankDistrict']) : '';
                $value['settle_data']['bankAddress'] = $bankProvince . ' ' . $bankCity . ' ' . $bankDistrict;
            }

            // 添加时间
            $value['add_time'] = date('Y-m-d H:i:s', $value['add_time']);

            // 覆盖原数据
            $list[$key] = $value;
        }

        $pageStr = $pageObj->show();
        // 数据返回
        $withdrawAssign = [
            'list' => $list,
            'page' => $pageStr,
            'pager' => $pageObj,
        ];
        return $withdrawAssign;
    }
}